import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, Item, AlertController } from 'ionic-angular';
import { COMBO_DATA } from '../../../common/combo'
import { ApiProvider } from '../../../providers/api/api';
import { NotificationProvider } from '../../../providers/notification/notification';
import { StorageProvider } from '../../../providers/storage/storage';
import { ToolProvider } from '../../../providers/tool/tool';
import { Observable } from 'rxjs';
import { HttpParams } from '@angular/common/http';
import { ZBar, ZBarOptions } from '@ionic-native/zbar';
import { PAGE_COUNT } from '../../../app/app.constants';

/**
 * Generated class for the InstorePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-instore',
  templateUrl: 'instore.html'
})
export class InstorePage {
  private houses: any;
  private userId: string;
  private userName: string;
  private houseId: string;
  private memo: string;
  private storeTypes = COMBO_DATA.storeType;
  private storeType: string = '1';
  private details = [];
  private fkeyid: string;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private api: ApiProvider,
    private notification: NotificationProvider,
    private modalCtrl: ModalController,
    private storage: StorageProvider,
    private tool: ToolProvider,
    private zbar: ZBar,
    private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    let userinfo = this.storage.getObject('userinfo');
    this.userId = userinfo.user_id;
    this.userName = userinfo.user_name;

    let res = this.api.getList('sp_house', { where_sql: 'sp_house.house_level=1', where_type: '', where_value: '' }).subscribe(res => {
      if (res['success']) {
        this.houses = res['data']['root'];
      } else {
        this.notification.showAlert(res['message']);
      }
    })
  }

  /**
   * 打开选择modal
   */
  selSpare() {
    let modal = this.modalCtrl.create('SpareSelPage');
    let isExist = false;
    modal.onDidDismiss(data => {
      //数组的追加
      if (data) {
        this.details.forEach(item => {
          if (data.sp_catalog__sp_id == item.sp_catalog__sp_id) {
            this.notification.showToast("不能重复选择货品");
            isExist = true;
          }
        });
        if (!isExist) this.details.push(data);
      }
    })
    modal.present();
  }


  /**
   * 打开选择modal
   */
  selUser() {
    let modal = this.modalCtrl.create('UserSelPage');
    modal.onDidDismiss(data => {
      if (data) {
        this.userId = data.sys_user__user_id;
        this.userName = data.sys_user__user_name;
      }
    })
    modal.present();
  }

  delete(item) {
    this.details.splice(item);
  }

  getData(event, item) {
    item.sp_catalog__in_num = event.number;
  }

  /**
   * 
   * @param index
   */
  edit(index) {
    //this.selIndex = index;
    this.details[index].sp_catalog__house_id = this.houseId || '';
    this.details[index].sp_catalog__in_memo = '';
    let modal = this.modalCtrl.create('SpareEditPage', { item: this.details[index] });
    modal.onDidDismiss(data => {
      if (data) {
        this.details[index] = data;
      }
    })
    modal.present();
  }

  /**
   * 提交表单
   */
  commit() {
    //提示确认
    this.notification.showConfirm('提示', '是否提交该单据？', res => {
      if (res == 0) return;
      this.notification.showLoading("正在提交");
      //校验数据
      if (!this.validForm) return;
      //提交主表数据
      this.api.formSave(this.getFormParams())
        .subscribe(res => {
          if (!res['success']) {
            this.notification.hideLoading();
            this.notification.showToast(res['message']);
            return;
          }
          this.fkeyid = res['data'].keyid;
          this.api.gridSave(this.getGridParams()).subscribe(res => {
            if (!res['success']) {
              //res['message']
              this.notification.hideLoading();
              this.notification.showToast("请完善入库信息");
              return;
            }
            this.api.formAudit('sp_in', this.fkeyid).subscribe(res => {
              if (res['success']) {
                this.notification.hideLoading();
                this.notification.showToast("入库单已提交");
                this.navCtrl.pop();
              } else {
                this.notification.hideLoading();
                //res['message']
                this.notification.showToast(res['message']);
                return;
              }
            })
          })
        })
    });
  }
  /**
   * 校验表单数据
   */
  validForm(): boolean {
    if (!this.houseId) {
      this.notification.showToast("请选择仓库");
      return false;
    }
    if (!this.details || this.details.length == 0) {
      this.notification.showToast("请选择产品");
      return false;
    }
    this.details.forEach(detail => {
      let price = detail.sp_catalog__tax_price;
      let stock = detail.sp_catalog__stock_id;
      if (!price) {
        this.notification.showToast("请填写价格");
        return false;
      }
      /** if(!stock){
        this.notification.showToast("请选择库位");
        return false;
      }*/
    });
    return true;
  }

  //获取表单参数
  getFormParams() {
    let userinfo = this.storage.getObject('userinfo'); //当前用户
    let houseName = '';
    let funid = '';
    this.houses.forEach(item => {
      if (item.sp_house__house_id == this.houseId) houseName = item.sp_house__house_name;
    });
    if (this.storeType == '1') {
      funid = 'sp_in';
    } else {
      funid = 'sp_in_other';
    }
    return {
      funid: funid,
      keyid: '',
      sp_in__auditing_in: '0',
      sp_in__user_name: userinfo.user_name,
      sp_in__house_user: this.userName,
      sp_in__house_id: this.houseId,
      sp_in__dept_id: userinfo.dept_id,
      sp_in__in_code: '',
      sp_in__dept_name: userinfo.dept_name,
      sp_in__house_name: houseName,
      sp_in__in_id: '',
      sp_in__in_date: this.tool.getToday(),
      sp_in__store_type: this.storeType,
      sp_in__user_id: userinfo.user_id,
      sp_in__house_userid: this.userId,
      sp_in__in_memo: this.memo || ''
    }
  }

  /**
   * 获取明细数据
   */
  getGridParams(): string {
    let urlParams = 'funid=sp_in_det&&pfunid=sp_in&app_id=jxstar&fkValue=' + this.fkeyid + '&';
    if (!this.details || this.details.length == 0) return;
    this.details.forEach(item => {
      let indet = {
        keyid: '',
        sp_in_det__sp_code: item.sp_catalog__sp_code,
        sp_in_det__sp_name: item.sp_catalog__sp_name,
        sp_in_det__sp_type: item.sp_catalog__sp_type,
        sp_in_det__other_code: item.sp_catalog__other_code,
        sp_in_det__unit: item.sp_catalog__unit,
        sp_in_det__in_num: item.sp_catalog__in_num,
        sp_in_det__stock_name: item.sp_catalog__stock_name,
        sp_in_det__stock_code: item.sp_catalog__stock_code,
        sp_in_det__tax_price: item.sp_catalog__tax_price,
        sp_in_det__tax_money: item.sp_catalog__tax_money,
        sp_in_det__in_memo: '',
        sp_in_det__in_det_id: '',
        sp_in_det__in_id: this.fkeyid,
        sp_in_det__sp_id: item.sp_catalog__sp_id,
        sp_in_det__stock_id: item.sp_catalog__stock_id
      }
      if (urlParams) urlParams += '&';
      urlParams += this.tool.parseParams(indet);
    });
    return urlParams;
  }

  scan() {
    let options: ZBarOptions = {
      flash: 'off',
      text_title: '二维码扫描',
      text_instructions: '请将镜头对准二维码',
      drawSight: false
    };

    this.zbar.scan(options)
      .then(result => {
        //alert("结果：" + result); // Scanned code
        this.notification.showLoading();
        let isExist = false;
        let option = {
          start: 0,
          limit: PAGE_COUNT,
          where_sql: 'sp_code=?',
          where_type: 'string',
          where_value: result
        }
        let res = this.api.getListPage('sp_catalog', option).subscribe(res => {
          if (res['success']) {
            let newItems = res['data']['root'];
            if (newItems && newItems.length == 1) {
              let data = newItems[0];
              data.sp_catalog__in_num = 1
              data.sp_catalog__tax_price = 0;
              data.sp_catalog__stock_id = '';
              data.sp_catalog__stock_code = '';
              data.sp_catalog__stock_name = '';
              this.details.forEach(item => {
                if (data.sp_catalog__sp_id == item.sp_catalog__sp_id) {
                  this.notification.showToast("不能重复选择货品");
                  isExist = true;
                }
              });
              if (!isExist) this.details.push(data);
            } else {
              this.notification.showToast("未识别或未找到匹配项！");
            }
          } else {
            this.notification.showAlert(res['message']);
          }
          this.notification.hideLoading();
        })
      })
      .catch(error => {
        if (error != 'cancelled')
          this.notification.showAlert(error); // Error message
      });
  }

}
